import 'dart:convert';

import 'package:chop/Model/ajax_request_entity.dart';
//import 'package:chop/view/Driver/Driverhome.dart';

import 'package:chop/view/home/home_page.dart';
//import 'package:chop/view/order/order_unfinished.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:get/get.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'SPUtils.dart';
import 'StringUtils.dart';
import 'configs.dart';

// 创建实例
WebSocketChannel _channel;
final flutterWebviewPlugin = FlutterWebviewPlugin();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

class MsgUtils{
  static initSocket(){
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin.initialize(initSetttings,
        onSelectNotification: onSelectNotification);
    SPUtils.get("UID").then((UID) async {
      String room = await SPUtils.get("room");
      if (StringUtils.isNull(UID)) {
        print("未登陆账号无法连接到服务器——————————————————");
//        _channel = IOWebSocketChannel.connect("${Configs.WEBSOCKET}$room-");
      }else{
        _channel = IOWebSocketChannel.connect("${Configs.WEBSOCKET}$room-$UID");
        // 监听消息
        _channel.stream.listen(onData,
            onDone: onDone,
            onError: onError);
      }

    });
  }
  static FlutterWebviewPlugin getWebView(){
    return flutterWebviewPlugin;
  }
  static Future onSelectNotification(String payload) {
    debugPrint("payload : $payload");
    if(payload == "新订单通知"){
//      Get.off(Driverhome());
    }
  }

  static showNotification() async {
    var android = new AndroidNotificationDetails(
        'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
        priority: Priority.High, importance: Importance.Max);
    var iOS = new IOSNotificationDetails();
    var platform = new NotificationDetails(android, iOS);
    await flutterLocalNotificationsPlugin.show(
        0, '新订单通知', '有新订单通知', platform,
        payload: '新订单通知');
  }

  static void onData(data){
    print("socket收到消息：$data");
    if(data == "ping"){
      print("心跳反馈");
    }else{
      Map m = json.decode(data);
      AjaxRequest aj = AjaxRequest.fromJson(m);
      if(aj.msg == "支付成功"){
        PayCom(m);
      }else if(aj.msg == "新订单"){
        print("123");
        showNotification();
      }
    }
  }

  static void PayCom(Map m) async {
    String orderID = m['data'];
    String TID = await SPUtils.get("TID");
    if(TID != orderID){
      SPUtils.save("TID", orderID);
      flutterWebviewPlugin.close();
      print("$orderID,关闭交易窗口");
//      await Get.to(OrdedrUnfinished());
      Get.offAll(homePage());
    }
  }

  static WebSocketChannel getChannel(){
    return _channel;
  }

  static void onDone() async {
    String room = await SPUtils.get("room");
    String UID = await SPUtils.get("UID");
    debugPrint("Socket is closed");
//    await _channel.sink.close();
    _channel = IOWebSocketChannel.connect("${Configs.WEBSOCKET}$room-$UID");
    _sendMessage("ping");
  }

  static void onError(err) {
    debugPrint(err.runtimeType.toString());
    WebSocketChannelException ex = err;
    debugPrint(ex.message);
  }
  static void _sendMessage(msg) {
    _channel.sink.add(msg);
  }

  static void colseChannel(){
    _channel.sink.close();
  }
}